//* Copyright(C) 2005-2012, all rights reserved.
//*
//* The following code is copyrighted and contains proprietary information
/* and trade secrets of Foxit Software Inc.      
**************************************************************************
*/

/**
* BoorkMark插件类；
* 需求的plugin: navigation panel;
*/



define(function (require, exports, module) {
    var CPDF_BookMark = require("./PDFBookmark");
    function FXBookmarkNode(parentNodeId, curNodeId, pdfBookmark) {
        this._parentNodeId = parentNodeId;
        this._curNodeId = curNodeId;
        this.pdfBookmark = pdfBookmark;
        this._childNodeList = [];

        this.AddChildNode = function (childNode) {
            this._childNodeList.push(childNode);
        };

        this.BindEvents = function (panel, dtree) {
            /*   var clickevent = "click";
            var curID = this._curNodeId;
            var _self = this;
            $("#ibm_" + this._curNodeId).bind(clickevent, function () {
            dtree.setCurNode(curID);
            g_ReaderApp.GetViewManager().GotoPageByDest(_self.pdfBookmark.GetBookmarkInfo()._DestInfo);
            return false;
            });
            $("#bm_" + this._curNodeId).bind(clickevent, function () {
            dtree.setCurNode(curID);
            g_ReaderApp.GetViewManager().GotoPageByDest(_self.pdfBookmark.GetBookmarkInfo()._DestInfo);
            return false;
            });

            if (this._childNodeList.length > 0) {
            $("#hcbm_" + this._curNodeId).bind(clickevent, function () {
            dtree.o(curID);
            panel.ReSetScroll();
            return false;
            });
            }*/
        }
    }


    var FXBookmarkTree = function (pReaderApp) {
        var _root = null;
        var _pReaderApp = pReaderApp;
        var _dtree = new dTree('bm_', 'bookmarkNode', 'bookmarkPlusItem');
        //public
        this.CreateTree = function (pdfbookmarkRoot){
            _root = new FXBookmarkNode(-1, 0, pdfbookmarkRoot);
            
            _dtree.add(_root._curNodeId, _root._parentNodeId, "");
            _EnumBookmark(_root, pdfbookmarkRoot);
            
        };
        
        this.ToHtmlString = function () {
            return _dtree.toString();
        };
        this.BindEvents = function (panel) {
        	$('.bookmarkNode').live('click', function (event) {
                try {
                    var nNodeID = parseInt(event.target.getAttribute("nodeid"));
                    var pBookMarkNode = _GetBookmarkNodeByID(_root, nNodeID);
                    if (pBookMarkNode != null) {
                        _dtree.setCurNode(nNodeID);
						var wapNavigationPanelPlugin = _pReaderApp.GetPluginByName(FXREADER.WapNavigationPanelPluginName);
						if(wapNavigationPanelPlugin != null)
						{
							wapNavigationPanelPlugin.Hide();
						}
                        _pReaderApp && _pReaderApp.GetMainView().GetDocView().GotoPageByDest(pBookMarkNode.pdfBookmark.GetBookmarkInfo()._DestInfo);
                        return false;
                    }
                }
                catch (ex) {
                    throw ex;
                }
            });
            $('.bookmarkPlusItem').live('click', function (event) {
                try {
                    var nNodeID = parseInt(event.target.getAttribute("nodeid"));
                    var pBookMarkNode = _GetBookmarkNodeByID(_root, nNodeID);
                    if (pBookMarkNode != null) {
                        _dtree.o(nNodeID);
                        panel.ReInitializeScroll();
                        return false;
                    }
                }
                catch (ex) {
                    throw ex;
                }
            });
            
            /*$('.dTreeNode').bind('touchstart touchend', function(e) {
                $(this).toggleClass('dTreeNodeHover');
            });*/

        };


        //private
        //根据ID获取节点
        function _GetBookmarkNodeByID(pBookMarkNode, ID) {
            if (pBookMarkNode == null)
                return null;
            if (pBookMarkNode._curNodeId == ID)
                return pBookMarkNode;
            var iChildLen = pBookMarkNode._childNodeList.length;
            for (var i = 0; i < iChildLen; i++) {
                var pFindChild = _GetBookmarkNodeByID(pBookMarkNode._childNodeList[i], ID);
                if (pFindChild != null)
                    return pFindChild;
            }
            return null;
        }
        

        
        function _BindNodeEvents(panel, node) {
            if (node != _root)
                node.BindEvents(panel, _dtree);
            var nSize = node._childNodeList.length;
            for (var k = 0; k < nSize; k++)
                _BindNodeEvents(panel, node._childNodeList[k]);
        }
        function _EnumBookmark(parentNode, parentPDFBK) {
            var nSize = parentPDFBK.GetChildCount();
            for (var k = 0; k < nSize; k++) {
                var childNode = _AddBookmarkNode(parentNode, parentPDFBK.GetChild(k));
                _EnumBookmark(childNode, parentPDFBK.GetChild(k));
            }
        }
        function _AddBookmarkNode(parentNode, curPDFBK) {

            var bookmarkNode = new FXBookmarkNode(parentNode._curNodeId, curPDFBK.GetBookmarkInfo()._nCurID, curPDFBK);
            parentNode.AddChildNode(bookmarkNode);
            var bmTitle = FXREADER.Common.htmlspecialchars(curPDFBK.GetBookmarkInfo()._szTitle);
            _dtree.add(bookmarkNode._curNodeId, bookmarkNode._parentNodeId, bmTitle);
            return bookmarkNode;
        }

    };


    FXREADER.CBookmarkPlugin = function (pReaderApp) {
        var _pReaderApp = pReaderApp,
        //bookmark
              _BookmarkRoot = null,
              _BookmarkTree = null,
              _ScrollApi = null,
        //是否已经取完数据;
              _bBookmarkDataInited = false,
               _Language = _pReaderApp.GetLanguage(),
              _self = this;

        //private members
        function _Init(jsonBookmarkData) {
            _BookmarkRoot = new CPDF_BookMark(null);
            _BookmarkRoot.parserBookmarkInfo(jsonBookmarkData);
            
            _BookmarkTree = new FXBookmarkTree(_pReaderApp);
            _BookmarkTree.CreateTree(_BookmarkRoot);
            _ToHtmlDiv();
            _AddScroll();
            _bBookmarkDataInited = true;
        }

        function _ToHtmlDiv() {
            $("#" + _self.GetPanelID()).append(_BookmarkTree.ToHtmlString());
            _BookmarkTree.BindEvents(_self);
        }

        function _AddScroll() {
            if (_ScrollApi == null) {
                var api_element = $('#' + _self.GetPanelID()).jScrollPane({ showArrows: false, animateScroll: false,initTouchScreen:true,disableHorizontalScroll:true });
                _ScrollApi = api_element.data('jsp');
            }
        }

        //public members
        //下面实现 INavigationChildPanel接口;
        this.GetPanelID = function () {
            return "fxBookmarkPanel";
        }
        this.GetTabBtnID = function () {
            return "bmtab";
        }
        this.GetTabNorImgUrl = function () {
            return "./images/bookmark_nor.png";
        }
        this.GetTabHotImgUrl = function () {
            return "./images/bookmark_nor.png";
        }
        this.GetTitle = function () {
            return _Language.BookMark.Title;
        }
        this.OnSize = function (nPanelWidth, nPanelHeight) {
            $("#" + _self.GetPanelID()).css({ width: nPanelWidth, height: nPanelHeight });
            if (_bBookmarkDataInited) {
                if (_ScrollApi == null) {
                    _AddScroll();
                }
                else
                    _ScrollApi.reinitialise();
            }
        }
        //end INavigationChildPanel接口;

        this.ReInitializeScroll = function () {
            _ScrollApi && _ScrollApi.reinitialise();
        }

        //获取Plugin名称;
        this.GetPluginName = function () {
            return "Boorkmark Plugin";
        }
        //插件被注册的时候调用;
        this.PIOnRegister = function () {
        }
        //模块初始化;
        this.PIInit = function () {
            _self.GetBookmarkData(FXREADER.Config.requestRetryCount);
        }
        //模块卸载;
        this.PIUnload = function () {
        }

        this.GetReaderApp = function () {
            return _pReaderApp;
        }


        //从网络上获取Bookmark数据;
        this.GetBookmarkData = function (retryCount) {
        	if (retryCount <= 0) {
                throw new Error('Maximum number of retries exceeded for GetBookmarkData request.');
            }
            var data = { fileid: pReaderApp.GetFileID() };
            $.ajax({
                url: FXREADER.Config.Url.GetBookmarkData,
                type: 'POST',
                dataType: 'json',
                data: data,

                success: function (response) {
                    var error = response.error;
                    if (error != 0) {
                    	 if (FXREADER.Common.IsNeedRetry(response.status)) {
                    		 var interval = FXREADER.AjaxRetryManager.GetNextBookmarkDataRequestInterval(_self.GetReaderApp().GetMainView().GetDocView().GetPageCount());
                             setTimeout(function () { _self.GetBookmarkData(retryCount - 1); }, interval);
                             return;
                         }
                         else {
                             throw new Error('Get Bookmark Data Error:' + error);
                             return;
                         }
                    }
                    try {
                        var jsonBookmarkData = $.parseJSON(response.BookmarkInfo);
                        if (jsonBookmarkData != null) {
                            _Init(jsonBookmarkData);
                            _pReaderApp.StepProgress();
                        }
                    }
                    catch (ex) {
                        throw ex;
                        return false;
                    }


                },
                error: function () {
                    throw new Error('Get Bookmark Data Error!');
                }
            });
        }

        this.GetRootBookmark = function () { return _BookmarkRoot; }

    }

    exports.Reader_CreatePlugin = function (pReaderApp) {
        var pBookmarkPlugin = new FXREADER.CBookmarkPlugin(pReaderApp);
        return pBookmarkPlugin;
    }
});